<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Service\AdaPayService;
use App\Http\Util\Tool;
use App\Jobs\CheckBleOrder;
use App\Jobs\CheckOrder;
use App\Jobs\PushMessage;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\Business;
use App\Model\CashDisabled;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\DeviceBus;
use App\Model\DeviceLog;
use App\Model\Order;
use App\Model\Device;
use App\Model\UserCashLog;
use App\Model\UserRefund;
use App\Service\baofu\Util\Tools;
use App\Service\BaofuPay;
use App\User;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use App\Http\Service\DeviceService;
use App\Model\UserAmountLog;
use App\Model\Message;
use App\Model\Bill;
use App\Model\BillPay;
use App\Contract\OrderType;
use Illuminate\Support\Facades\Redis;

class OrderController extends Controller
{

    public function orderStatus(Request $request)
    {
        Log::notice('orderStatus', [$request->all()]);
        $orderNo = $request->input('orderNo');

        $order = Order::query()->where('order_no', $orderNo)->first();
        if (!$order) {
            return Result::error(401, '订单不存在');
        }
        if ($order->status == 3) {
            return Result::success(['is_paid' => 1]);
        }
        return Result::success(['is_paid' => 0]);
    }

    public function orderFailList(Request $request)
    {
        $deviceId = $request->input('deviceId');
        $order = Order::query()->where('device_id', $deviceId)
            ->where('recharge_status', 2)
            ->where('status', 3)
            ->with('device')->first();
        if (!$order) {
            $order = Order::query()->where('device_id', $deviceId)
                ->where('recharge_status', 0)
                ->where('paid_at', '<', Carbon::now()->subSecond(40))
                ->where('status', 3)
                ->with('device')->first();
        }
        return Result::success(['fail' => $order]);
    }

    # 4G设备充值
    public function recharge(Request $request)
    {
        $orderNo = $request->input('orderNo');
        $order = Order::query()->with('device')->where('order_no', $orderNo)->first();

        if (!$order or $order->status != 3) {
            return Result::error(401, '订单无效');
        }
        if ($order->recharge_status != 0) {
            return Result::error(401, '订单状态错误');
        }
        $deviceModel = $order->device;
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
//        if(!$deviceModel->read_at){
//            return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
//        }
//        $targetTime = strtotime($deviceModel->read_at);
//        $currentTime = time();
//        if ($targetTime < ($currentTime - 60)) {
//            return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
//        }
        $type = $request->input('type','add');
        $service = app()->make(DeviceService::class);
        if($deviceModel->mac && $type == 'edit'){
            $du = $order->device_du+$order->du;
            $diff = $order->device_du-$deviceModel->du;
            if($diff > 0){
                $du-=$diff;
            }
            $result = $service->secondRecharge($deviceModel->mac, $du, $order->pay_amt);
        }else{
            $result = $service->simpleRecharge($deviceModel->mac, $order->du, $order->pay_amt);
        }
        $order->recharge_status = 1;
        $order->save();
        $key = 'ORDER_' . $orderNo;
        Redis::setex($key, 20 * 60, $deviceModel->du);
        dispatch(new CheckOrder($orderNo))->delay(30);
        return Result::success();
    }

    # 蓝牙设备充值
    public function bleRecharge(Request $request)
    {
        $orderNo = $request->input('orderNo');
        $order = Order::query()->with('device')->where('order_no', $orderNo)->first();
        if (!$order or $order->status != 3) {
            return Result::error(401, '订单无效');
        }
        if ($order->recharge_status != 0) {
            return Result::error(401, '订单状态错误');
        }
        $deviceModel = $order->device;
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $order->recharge_status = 1;
        $order->save();
        $key = 'ORDER_' . $orderNo;
        Redis::setex($key, 20*60, $deviceModel->du);
        dispatch(new CheckBleOrder($orderNo))->delay(60);
        return Result::success();
    }

    # 失败订单重新充值
    public function tryRecharge(Request $request)
    {
        $orderNo = $request->input('orderNo');
        $order = Order::query()->with('device')->where('order_no', $orderNo)->first();
        if (!$order or $order->status != 3) {
            return Result::error(401, '订单无效');
        }
        if ($order->recharge_status == 3) {
            return Result::error(401, '补充值已成功，请返回查看用电量');
        }

        if ($order->recharge_status != 2 && $order->recharge_status != 0) {
            return Result::error(401, '订单状态错误');
        }

        if($order->device->du > ($order->device_du+$order->du*0.2)){
            $latestOrder = Order::query()
                ->where('device_id', $order->device_id)
                ->where('recharge_status', 3)
                ->orderByDesc('id')
                ->first();
            if($latestOrder && $latestOrder->id != $order->id){
                $order->device_du = $order->device->du;
            }
//            $order->recharge_status = 3;
//            $order->save();
//            $user = User::query()->where('id',$order->user_id)->first();
//            $service = app()->make(DeviceService::class);
//            $service->addRechargeLog($order->device_id, $order->du, $order->pay_amt,$user,$order->paid_at);
//            return Result::error(401, '补充值已成功，请返回查看用电量');
        }
        $ttl =$order->checkCache();
        if($ttl>0){
            $min = round($ttl/60) < 1 ?1:round($ttl/60) ;
            return Result::error(401, '当前信号不稳定，请'.$min.'分钟后重试');
        }
        $order->recharge_status = 0;
        $order->save();

        return Result::success();
    }

    # 充值失败
    public function rechargeFail(Request $request)
    {
        $orderNo = $request->input('orderNo');
        $before = $request->input('before', 0);
        $after = $request->input('after', 0);
        $order = Order::query()->with('device')->where('order_no', $orderNo)->first();
        if (!$order or $order->status != 3) {
            return Result::error(401, '订单无效');
        }
        if(Redis::exists('CHECK_CACHE_'.$orderNo)){
            return Result::success([]);
        }
        if ($order && $order->recharge_status <= 1) {
            $order->recharge_status = 2;
            $order->save();
            // 增加日志
            $service = app()->make(DeviceService::class);
            $service->addRechargeFailLog($order->device_id, $order->du, $order->pay_amt, $before, $after);
            $order->setCache();
            return Result::success([]);
        }

        return Result::error(401, '订单状态无效');
    }

    public function getTodayCount(Request $request)
    {
        $sn = $request->input('sn');
        $device = Device::query()->where('sn', $sn)->first();
        $key = 'BUSINESS_RECHARGE_CACHE' . date('Ymd') . $device->id;
        if (Redis::exists($key)) {
            Redis::incrBy($key, 1);
        } else {
            Redis::setex($key, 60 * 60 * 24, 1);
        }
        $data['count'] = Redis::get($key);
        return Result::success($data);
    }

    public function getOrderDetail(Request $request){
        $deviceId = $request->input('device_id');

        $order = Order::query()->with('device')->where('device_id', $deviceId)
            ->where('type',OrderType::TEMP)
            ->where('status',5)
            ->orderBy('id','desc')
            ->first();
        return Result::success($order);
    }

    public function tempList(Request $request){
        $user = $this->getUser();
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $order = Order::query()->where('type',OrderType::TEMP)
            ->where('user_id',$user->id)
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success($order);
    }


    public function BusinessTempList(Request $request){
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $deviceId = $request->input('device_id');
        $order = Order::query()->where('type',OrderType::TEMP)
            ->where('device_id',$deviceId)
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success($order);
    }

    public function tempEnd(Request $request){
        $orderNo = $request->input('orderNo');
        $type = $request->input('type','4G');
        $order = Order::query()->with('device', 'business', 'business.user', 'user')->where('order_no', $orderNo)->first();
        if (!$order or $order->status != OrderType::TEMP) {
            return Result::error(401, '订单无效');
        }
        $user = User::query()->where('id', $order->user_id)->first();
        if($type == '4G'){
            $diff = $order->device->total - $order->device_total;
            $diff = $diff>0?$diff:0;
        }else{
            $diff = $request->input('diff',0);
        }
        $use_amount = $order->device_price*$diff;
        if($user){
            $userName = $user->nickame;
            if(!$userName){
                $userName = $user->mobile;
            }
        }else{
            $userName = $this->getUserName();
        }
        DeviceLog::create([
            'action' => 9,
            'device_id' => $order->device_id,
            'log' => '租客临时用电' . $diff . '度',
            'amount' => $use_amount,
            'user_name' => $userName,
            'before'=>$order->device_total,
            'after'=>$order->device->total,
            'created_at'=>$order->paid_at
        ]);
        $return_fee =$order->pay_amt-$order->fee-$use_amount;
        $order->diff = $diff;
        if ($order->device_id) {
            $deviceModel = Device::query()->where('id', $order->device_id)->first();
            if($type == '4G'){
                $service = app()->make(DeviceService::class);
                $result = $service->clear($deviceModel->mac);
            }
            if ($deviceModel->agent_id) {
                $agentModel = Agent::query()->where('id', $deviceModel->agent_id)->first();
                $allRate = number_format($order->pay_amt * (Agent::MAX_RATE / 100), 2,'.', '');
                try {
                    if ($agentModel->pid) {
                        $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                        $agentType = $firstAgent->type;
                    } else {
                        $firstAgent = $agentModel;
                        $agentType = $agentModel->type;
                    }
                    if ($agentType == 2) {

                    } else {
                        if ($agentModel->rate) {
                            if ($agentModel->rate > 0.3) {
                                $agentModel->rate = 0.3;
                            }
                            $secAmount = number_format($order->pay_amt * $agentModel->rate / 100, 2, '.', '');
                            AgentAmountLog::create([
                                'agent_id' => $agentModel->id,
                                'type' => $order->type,
                                'amount' => $secAmount,
                                'order_id' => $order->id,
                                'log' => '临时用电（线上）分润收入'
                            ]);

                            $agentModel->amount += $secAmount;
                            $agentModel->total_amount += $secAmount;
                            $agentModel->total_fee += ($order->pay_amt-$return_fee);
                            $agentModel->save();
                            $firstAmount = $allRate - $secAmount;
                            if ($firstAmount > 0 && $agentModel->pid) {
                                AgentAmountLog::create([
                                    'agent_id' => $firstAgent->id,
                                    'type' => $order->type,
                                    'amount' => $firstAmount,
                                    'order_id' => $order->id,
                                    'log' => '临时用电（线上）分润收入'
                                ]);
                                $firstAgent->amount += $secAmount;
                                $firstAgent->total_amount += $secAmount;
                                $firstAgent->total_fee += ($order->pay_amt-$return_fee);
                                $firstAgent->save();
                            }
                        }
                    }
                } catch (\Exception $e) {

                }
            }
        }
        // 写入房东余额
        $fd = $order->business->user;
        $fd->amount += $use_amount;
        $fd->total_amount += $use_amount;
        $fd->save();
        $order->status = 4;
        $order->save();
        $bill = new Bill();
        $bill->fill([
            'business_id' => $order->business_id,
            'mobile' => $order->user->mobile,
            'house_id' => $order->house_id,
            'device_id' => $order->device_id,
            'title' => '临时用电'.number_format($use_amount,2),
            'amount' => number_format($use_amount,2),
            'type' => OrderType::ELECTRIC,
            'is_paid' => 1,
            'paid_at' => $order->paid_at,
            //'pay_date' => now()->toDateString(),
        ]);
        $bill->save();
        if($return_fee > 0){
            $refund_no = 'NR'.rand(99,999).$order->order_no;
                $refund = AdaPayService::refund();
                $params = array(
                    "payment_id"=> $order->payment_id,
                    # 退款订单号
                    "refund_order_no"=> $refund_no,
                    # 退款金额
                    "refund_amt"=> number_format($return_fee,2),
                    "notify_url" => env('APP_URL') .'/api/payment/notify'
                );
                $refund->create($params);
                if ($refund->isError()) {
                    return Result::error(500, '创建退款失败');
                }
                $save['order_no'] = $order->order_no;
                $save['amount'] = $return_fee;
                $save['type'] = 2;
                $save['remark'] ='临时用电退款';
                $save['refund_no'] = $refund_no;
                $save['error_msg'] = json_encode($refund->result);
                UserRefund::create($save);
        }

        if($fd->account_id && $fd->auto_cash){
            $bfAccount  = app::make(BaofuPay::class);
            $drawResult['balance'] = $bfAccount->subAccount($use_amount,$fd);
            if($drawResult['balance']['retCode'] != 1 || $drawResult['balance']['state'] != 1){
                return Result::error(401, '划账失败请稍后重试');
            }
            $orderNo = Tools::getTsnOderid("TSN");
            $save = [
                'order_no' => $orderNo,
                'cash_type' =>'自动到账',
                'cash_amt' => $use_amount,
                'user_id' => $fd->id,
                'bank_name' => $fd->bank->bank_name,
                'card_id' => $fd->bank->card_id,
                'card_type' => $fd->bank->bank_acct_type,
                'card_name' => $fd->bank->card_name
            ];
            $cashLog = UserCashLog::create($save);
            $drawResult['draw'] = $bfAccount->transferCash($use_amount,$fd,$orderNo);
            if($drawResult['draw']['retCode'] != 1 || $drawResult['draw']['state'] != 1){
                return Result::error(401, '发起取现失败请稍后重试');
            }
            $fd->amount -=$use_amount;
            $fd->save();
            // 写入账户明细
            UserAmountLog::create([
                'user_id' => $fd->id,
                'type' => 5,
                'amount' => $use_amount,
                'log' => '提现支出'
            ]);
            // 写入记录
            $cashLog->error_msg = json_encode($drawResult);
            $cashLog->status = 2;
            $cashLog->save();
        }

        return Result::success($order);
    }

    # 充值成功
    public function rechargeSuccess(Request $request)
    {
        $orderNo = $request->input('orderNo');
        $identity = $request->input('identity', 1);
        $mode = $request->input('mode', 0);
        $description = $request->input('description');
        $order = Order::query()->with('device', 'business', 'business.user', 'user')->where('order_no', $orderNo)->first();
        if (!$order or $order->status != 3) {
            return Result::error(401, '订单无效');
        }
        $key = 'BUSINESS_RECHARGE_CACHE' . date('Ymd') . $order->device_id;
        if ($mode) {
            if (Redis::exists($key)) {
                Redis::incrBy($key, 1);
            } else {
                Redis::setex($key, 60 * 60 * 24, 1);
            }
        }
        $cacheKey = "bill_lock:{$order->id}";
        if (Redis::setnx($cacheKey, 1)) {
            Redis::expire($cacheKey, 1); // 1秒过期
            // 进入正式逻辑
        } else {
            Log::info('重复请求拒绝'.$order->id);
            return Result::success([]);
        }
        if ($order && $order->recharge_status < 3) {
            $order->recharge_status = 3;
            if($order->type == OrderType::TEMP){
                $order->status = 5;
                $order->save();
                return Result::success($order);
            }
            if($description){
                $order->description = $description;
            }
            $order->save();
            $order->checkDraw();
            if($order->is_draw == 0){
                $service = app()->make(DeviceService::class);
                $user = User::query()->where('id', $order->user_id)->first();
                $service->addRechargeLog($order->device_id, $order->du, $order->pay_amt, $user,$order->paid_at);
                $amount = $order->pay_amt - $order->fee;
                if ($order->device_id) {
                    $deviceModel = Device::query()->where('id', $order->device_id)
                        ->with('business')->first();
                    if($description){
                        $deviceModel->recharge_callback_at = Carbon::now()->toDateTimeString();
                        $deviceModel->save();
                    }
                    if ($deviceModel->agent_id) {
                        $agentModel = Agent::query()->where('id', $deviceModel->agent_id)->first();
                        $allRate = number_format($order->pay_amt * (Agent::MAX_RATE / 100), 2,'.', '');
                        try {
                            if ($agentModel->pid) {
                                $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                                $agentType = $firstAgent->type;
                            } else {
                                $firstAgent = $agentModel;
                                $agentType = $agentModel->type;
                            }
                            if ($agentType == 2) {
                                if(!$deviceModel->business->device_time || time() >= strtotime($deviceModel->business->device_time)){
                                    if($deviceModel->business->service > 0 && time() >= strtotime($deviceModel->business->device_time) ){
                                        $agent_service = $deviceModel->business->service;
                                    }else{
                                        $agent_service = $firstAgent->service;
                                    }
                                    $deviceFee = floor($agent_service * $order->du * 100) / 100;
                                    $firstFee = $deviceFee;
                                    if($firstAgent->rate > 0){
                                        $deviceProfit = ceil($amount * ($firstAgent->rate / 100) * 100) / 100;
                                    }else{
                                        $deviceProfit = 0;
                                    }
                                    $amount = floor($order->du * $order->device_price * 100) / 100;
                                    $firstFee= $deviceFee-$deviceProfit;
                                    if ($agentModel->pid && $firstFee > 0) {
                                        $secondFee = number_format($firstFee * $agentModel->service / 100, 2, '.', '');
                                        $firstFee -= $secondFee;
                                        if($secondFee > 0) {
                                            $agentModel->amount += $secondFee;
                                            $agentModel->total_amount += $secondFee;
                                            $agentModel->total_fee += $order->pay_amt;
                                            $agentModel->save();
                                            AgentAmountLog::create([
                                                'agent_id' => $agentModel->id,
                                                'type' => $order->type,
                                                'amount' => $secondFee,
                                                'order_id' => $order->id,
                                                'device_amount'=>$deviceFee,
                                                'log' => '设备管理费收入',
                                                'agent_type' => 2,
                                                'business_id'=> $order->business_id
                                            ]);
                                        }
                                    }
                                    if ($firstFee > 0) {
                                        $firstAgent->amount += $firstFee;
                                        $firstAgent->total_amount += $firstFee;
                                        $firstAgent->total_fee += $order->pay_amt;
                                        $firstAgent->save();
                                        AgentAmountLog::create([
                                            'agent_id' => $firstAgent->id,
                                            'type' => $order->type,
                                            'amount' => $firstFee,
                                            'device_amount'=>$deviceFee,
                                            'order_id' => $order->id,
                                            'log' => '设备管理费收入',
                                            'agent_type' => 2,
                                            'business_id'=> $order->business_id
                                        ]);
                                    }
                                }
                            } else {
                                if ($agentModel->rate) {
                                    if ($agentModel->rate > 0.3) {
                                        $agentModel->rate = 0.3;
                                    }
                                    $secAmount = number_format($order->pay_amt * $agentModel->rate / 100, 2, '.', '');
                                    AgentAmountLog::create([
                                        'agent_id' => $agentModel->id,
                                        'type' => $order->type,
                                        'amount' => $secAmount,
                                        'order_id' => $order->id,
                                        'log' => '电费充值（线上）分润收入'
                                    ]);

                                    $agentModel->amount += $secAmount;
                                    $agentModel->total_amount += $secAmount;
                                    $agentModel->total_fee += $order->pay_amt;
                                    $agentModel->save();
                                    $firstAmount = $allRate - $secAmount;
                                    if ($firstAmount > 0 && $agentModel->pid) {
                                        AgentAmountLog::create([
                                            'agent_id' => $firstAgent->id,
                                            'type' => $order->type,
                                            'amount' => $firstAmount,
                                            'order_id' => $order->id,
                                            'log' => '电费充值（线上）分润收入'
                                        ]);
                                        $firstAgent->amount += $firstAmount;
                                        $firstAgent->total_amount += $firstAmount;
                                        $firstAgent->total_fee += $order->pay_amt;
                                        $firstAgent->save();
                                    }
                                }
                            }
                        } catch (\Exception $e) {

                        }
                    }
                }

                // 写入账单
                // 生成电费账单
                $bill = new Bill();
                if($order->device->type == 2){
                    $type = OrderType::WATER;
                    $title = '水费充值:'.$order->du.'吨';
                }else{
                    $type = OrderType::ELECTRIC;
                    $title = '电费充值:'.$order->du.'度';
                }
                $check = Bill::where('type',$type)
                    ->where('paid_at',$order->paid_at)
                    ->where('device_id',$order->device_id)
                    ->first();
                if($check){
                    Log::info('已有该账单无需重复操作----'.$order->id);
                    return Result::success([]);
                }
                $bill->fill([
                    'business_id' => $order->business_id,
                    'mobile' => $order->user->mobile,
                    'house_id' => $order->house_id,
                    'device_id' => $order->device_id,
                    'title' => $title,
                    'amount' => $amount,
                    'type' => $type,
                    'is_paid' => 1,
                    'paid_at' => $order->paid_at,
                    'target_id'=>$order->id
                    //'pay_date' => now()->toDateString(),
                ]);
                $bill->save();
                // 写入房东余额
                $fd = $order->business->user;
                $fd->amount += $amount;
                $fd->total_amount += $amount;
                $fd->save();

                //推送小程序信息
                if($fd->sub_1 == 1 && $fd->sub_status == 1 && $fd->openid){
                    dispatch(new PushMessage($order,$fd->openid));
                }
                // 写入账户明细
                UserAmountLog::create([
                    'user_id' => $fd->id,
                    'type' => $order->type,
                    'amount' => $amount,
                    'order_id' => $order->id,
                    'log' => '线上支付收入'
                ]);
                // 写入房东消息
                Message::create([
                    'user_id' => $fd->id,
                    'title' => '账单支付成功通知',
                    'content' => '支付项目：' . $order->goods_desc . ' <br> 到账金额：￥' . $amount
                ]);

                $billPay = new BillPay();
                if ($identity == 2) {
                    $payment = $order->pay_channel == 'wx_lite' ? 6 : 7;
                } else {
                    $payment = $order->pay_channel == 'wx_lite' ? 4 : 5;
                }
                $billPay->fill([
                    'sn' => $order->order_no,
                    'bill_id' => $bill->id,
                    'amount' => $amount,
                    'payment' => $payment,
                    'is_paid' => 1,
                    'paid_at' => $order->paid_at
                ]);
                $billPay->save();
            }else{
                //draw之后的业务
                if($order->device->online_status != 1){
                    return Result::success(['decr'=>$order->du]);
                }else{
                    $service = app()->make(DeviceService::class);
                    $decTotal = round(($order->device->total-$order->du),2);
                    $service->setTotal($order->device->mac,$decTotal);
                    $num = 0;
                    $du = $order->du;
                    for($i=3;$i<10;$i++){
                        $month =  Tool::getThreeMonthsAgoMonth($i);
                        $monthKey = $order->device->id. '-' . str_replace('-', '', $month);
                        $monthVal = Redis::exists($monthKey)?Redis::get($monthKey):0;
                        if($monthVal > $du*1000){
                            $num = $i;
                            break;
                        }
                    }
                    if($num > 0 ){
                        $j = 0;
                        while($du > 1){
                            $du = Tool::decrCacheDu($order->device->id,$du,$num);
                            $j++;
                            if($j>20){
                                break;
                            }
                        }
                    }
                }
            }
            // 增加日志
            $busInfo = DeviceBus::query()->where('device_id', $order->device_id)
                ->first();
            if ($busInfo && $busInfo->recharge) {
                $device = Device::query()->where('id', $order->device_id)->first();
                $busInfo->device_total = $device->total;
                $busInfo->status = 1;
                $busInfo->save();
                $bus = DeviceBus::query()->where('id', $busInfo->pid)->first();
                if($bus && $bus->is_autoload){
                    $count = DeviceBus::query()->where('type', 2)
                        ->where('status',1)
                        ->where('pid', $busInfo->pid)->count();
                    $rate = number_format(100 /$count, 2);
                    DeviceBus::query()->where('type', 2)
                        ->where('pid', $busInfo->pid)
                        ->where('status',1)
                        ->update(['rate' => $rate]);
                }
            }
            if(Redis::exists('sub_warning_'.$order->device_id)){
                Redis::del('sub_warning_'.$order->device_id);
            }



            if($fd->account_id && $fd->auto_cash){

                if($fd->is_disabled == 1){
                    $errorLog = new CashDisabled();
                    $errorLog->error_msg = '账户异常(被禁用)';
                    $errorLog->amount = $amount;
                    $errorLog->user_id = $user->id;
                    $errorLog->mobile = $user->mobile;
                    $errorLog->save();
                    return Result::error(401, '账户异常 请联系客服400-926-2566');
                }
                $all_device = Device::query()->where('business_id',$fd->business->id)->get(['id']);
                $val = 0;
                foreach($all_device as $v){
                    $key = $v->id.'-'.date('Ym');
                    if (Redis::exists($key)) {
                        $val += Redis::get($key);
                    }
                }
                Log::info('auto-val---'.$val);
                if ($fd->white != 1 && $val<200*1000) {
                    $checkFirst = UserCashLog::query()->where('user_id', $fd->id)
                        ->where('status', 1)->count();
                    Log::info('auto-checkfirst---'.$checkFirst);
                    if ($amount <= 300 && $checkFirst == 0) {

                    } else {
                        $total = Device::query()->where('business_id', $fd->business->id)->sum('total');
                        Log::info('auto-total---'.$total);
                        if ($total < 100) {
                            $count = Device::query()
                                ->where('business_id', $fd->business->id)
                                ->where('net_type',1)
                                ->where('total_money','>',0)
                                ->count();
                            Log::info('auto-count---'.$count);
                            $useCount = Device::query()
                                ->where('business_id', $fd->business->id)
                                ->where('total','>=',3)
                                ->where('net_type',1)
                                ->count();
                            Log::info('auto-useCount---'.$useCount);
                            //  Log::info('count---'.$count.'---useCount----'.$useCount);
                            if($useCount < $count*0.5){
                                $errorLog = new CashDisabled();
//                        $errorLog->error_msg = '该用户名下'.$count.'台设备'.',总电量超过3度的为'.$useCount.'台设备,'.'名下所有表的总电量为'.$total.'度';
                                $errorLog->error_msg ='用电异常-自动打款失败';
                                $errorLog->amount = $amount;
                                $errorLog->user_id = $fd->id;
                                $errorLog->mobile = $fd->mobile;
                                $errorLog->save();
                                $business = Business::query()->where('user_id',$fd->id)->first();
                                if($business->agent_id <= 0 ){
                                    return Result::error(401,'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常导致自动打款失败，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：400-926-2566');
                                }else{
                                    $agent = Agent::where('id',$business->agent_id)->first();
                                    if($agent->tel_no){
                                        $tel_no = $agent->tel_no;
                                    }else{
                                        $tel_no = $agent->mobile;
                                    }
                                    return Result::error(401,'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常导致自动打款失败，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：'.$tel_no);
                                }
                            }
                        }
                    }
                }
                $bfAccount  = app::make(BaofuPay::class);
                $drawResult['balance'] = $bfAccount->subAccount($amount,$fd);
                if($drawResult['balance']['retCode'] != 1 || $drawResult['balance']['state'] != 1){
                    Log::info('划账失败-auto-balance'.json_encode($drawResult['balance']));
                    return Result::success([]);
                }
                $orderNo = Tools::getTsnOderid("TSN");
                $save = [
                    'order_no' => $orderNo,
                    'cash_type' =>'自动到账',
                    'cash_amt' => $amount,
                    'user_id' => $fd->id,
                    'bank_name' => $fd->bank->bank_name,
                    'card_id' => $fd->bank->card_id,
                    'card_type' => $fd->bank->bank_acct_type,
                    'card_name' => $fd->bank->card_name
                ];
                $order->is_auto = 1;
                $order->save();
                $cashLog = UserCashLog::create($save);
                $drawResult['draw'] = $bfAccount->transferCash($amount,$fd,$orderNo);
                if($drawResult['draw']['retCode'] != 1 || $drawResult['draw']['state'] != 1){
                    Log::info('auto-draw'.json_encode($drawResult['draw']));
                    return Result::error(401, '发起取现失败请稍后重试');
                }
                $fd->amount -= $amount;
                $fd->save();
                // 写入账户明细
                UserAmountLog::create([
                    'user_id' => $fd->id,
                    'type' => 5,
                    'amount' => $amount,
                    'log' => '提现支出'
                ]);
                // 写入记录
                $cashLog->error_msg = json_encode($drawResult);
                $cashLog->status = 2;
                $cashLog->save();
            }
            return Result::success([]);
        }

        return Result::error(401, '订单状态无效');
    }
}
